package com.mar.meclient.bt.impl;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.bluetooth.ServiceRecord;

import net.java.dev.marge.entity.ClientDevice;
import net.java.dev.marge.entity.config.ClientConfiguration;
import net.java.dev.marge.factory.CommunicationFactory;
import net.java.dev.marge.factory.L2CAPCommunicationFactory;
import net.java.dev.marge.factory.RFCOMMCommunicationFactory;

import com.mar.meclient.bt.BTMidlet;
import com.mar.meclient.bt.IBluetoothIOHandler;
/**
 * Ideally should be a pair for bluetooth Input and Output stream.
 * @author mar
 */
class BluetoothIOHandler implements IBluetoothIOHandler {
	
	private final BTOutputStream btOutputStream;
	private final BTInputStream btInputStream;
	private final ClientDevice btClientDevice; 
	
	BluetoothIOHandler( ServiceRecord serviceRecord ) throws IOException {
//		serviceRecord.setAttributeValue( L2CA, new DataElement())
		this.btInputStream = new BTInputStream();
		
		final CommunicationFactory factory = createCommunicationFactory();
        
		final ClientConfiguration clientConfig = createClientConfiguration(serviceRecord);
        
        this.btClientDevice = factory.connectToServer(clientConfig);
        
        //TODO: should be carefully configured
        //        this.btClientDevice.setReadInterval(1000);
        this.btOutputStream = new BTOutputStream(this.btClientDevice);
        
        //TODO: check if this is needed
//        this.btClientDevice.setCommunicationListener(communicationListaner);
        
        // Start listening
        //TODO:  extract may be to a separate method
        this.btClientDevice.startListening();
        
        BTMidlet.getInstance().addDestroyListener(new BTMidlet.IMidletDestroyListener(){
        	public void midletDestroyed() {
        		close();
        	}
        });
        
	}

	/* (non-Javadoc)
	 * @see com.mar.meclient.bt.IBluetoothIOHandler#getOutputStream()
	 */
	public OutputStream getOutputStream(){
		return btOutputStream;
	}
	
	/* (non-Javadoc)
	 * @see com.mar.meclient.bt.IBluetoothIOHandler#getInputStream()
	 */
	public InputStream getInputStream(){
		return btInputStream;
	}
	
	/* (non-Javadoc)
	 * @see com.mar.meclient.bt.IBluetoothIOHandler#close()
	 */
	public void close(){
		btClientDevice.stopListenning();
		btOutputStream.close();
	}

	// Implementation's factory methods
	
	protected CommunicationFactory createCommunicationFactory() {
		CommunicationFactory factory = new RFCOMMCommunicationFactory()/*new L2CAPCommunicationFactory()*/;
		return factory;
	}

	protected ClientConfiguration createClientConfiguration(ServiceRecord serviceRecord) {
		ClientConfiguration clientConfig = new ClientConfiguration(serviceRecord, btInputStream );
	    clientConfig.setReadInterval(100);//TODO:
		return clientConfig;
	}
}
